package com.blockmeta.bbs.businesslibrary.util;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.android.arouter.core.LogisticsCenter;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.businesslibrary.launch.SplashActivity;
import com.blockmeta.bbs.businesslibrary.util.navigation.DeepLinkContext;
import com.blockmeta.bbs.businesslibrary.widget.ForegroundCallbacks;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author airthor
 * Date 2018/4/12.
 */

public class DeepLinkUtils {
    public static void jumpToTarget(Context context, Uri uri) {
        if (uri == null || uri.getHost() == null) {return;}

           Postcard postcard = ARouter.getInstance().build(uri);

            Map<String,String> params = DeepLinkContext.getParams(uri);
            if (params!=null){
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    postcard.withString(entry.getKey(),entry.getValue());
                }
                jumpToTarget(context, postcard);
            }else {
                jumpToTarget(context, postcard);
            }

        DeepLinkContext.needPostEvents(uri);
    }

    private static void jumpToTarget(final Context context, Postcard postcard) {
        boolean isForeground = ForegroundCallbacks.get(BaseApp.getApp()).isForeground();
        if(isForeground) {
            postcard.navigation(context);
        }else {
            if(postcard == null){
                return;
            }
            LogisticsCenter.completion(postcard);
            Class<?> destination = postcard.getDestination();
            if(destination == null){
                return;
            }
            Intent[] intents = new Intent[2];
            intents[0] = new Intent(context, SplashActivity.class);
            Intent intent = new Intent(context, destination);
            intent.putExtras(postcard.getExtras());
            intents[1] = intent;
            context.startActivities(intents);
        }
    }

    public static String regexUri(String url) {
        if (TextUtils.isEmpty(url)){
            return "";
        }
        Uri uri = Uri.parse(url);
        String deeplinkScheme = "blockmeta://";
        if ("blockmeta".equals(uri.getScheme())){
            return url;
        }else if ("8btc.com".equals(uri.getHost())) {
            deeplinkScheme = getNewsDeepLink(url, uri, deeplinkScheme);
        }else if (uri.getHost()!=null&&(uri.getHost().contains("chainnode.com"))){
            //社区问答板块
            String askReg = "/ask";
            //问答板块详情
            String askDetailReg = "/question/([0-9]+)|/question/([0-9]+)-([0-9]+)";
            //社区AMA板块
            String amaReg = "/ask-me-anything";
            //AMA 详情页
            String amaDetailReg = "/ama/([0-9]+)|/ama/([0-9]+)-([0-9]+)";
            //论坛帖子详情
            String postReg = "/post/([0-9]+)|/post/([0-9]+)-([0-9]+)";
            //活动详情页面
            String activityReg = "/event/([0-9]+)|/event/([0-9]+)-([0-9]+)";
            //全部活动列表
            String activitiesReg = "/events";
            //论坛各板块分类
            String forumReg = "/forum/([0-9]+)";
            //文库
            String docReg = "/doc/([0-9]+)";
            //教程
            String tutorialReg = "/tutorial/([0-9]+)";
            //链作
            String chainthingReg = "/mall/item/([0-9]+)";

            String path = uri.getPath();

            Matcher askMatcher = Pattern.compile(askReg).matcher(path);
            Matcher askDetailMatcher = Pattern.compile(askDetailReg).matcher(path);
            Matcher amaMatcher = Pattern.compile(amaReg).matcher(path);
            Matcher amaDetailMatcher = Pattern.compile(amaDetailReg).matcher(path);
            Matcher postMatcher = Pattern.compile(postReg).matcher(path);
            Matcher activityMatcher = Pattern.compile(activityReg).matcher(path);
            Matcher activitiesMatcher = Pattern.compile(activitiesReg).matcher(path);
            Matcher forumMatcher = Pattern.compile(forumReg).matcher(path);
            Matcher docMatcher = Pattern.compile(docReg).matcher(path);
            Matcher tutorialMatcher = Pattern.compile(tutorialReg).matcher(path);
            Matcher chainthingMatcher = Pattern.compile(chainthingReg).matcher(path);

            if (amaMatcher.find()){
                //AMA列表页面
                deeplinkScheme = deeplinkScheme + "bbs/forum?fid=121";
            }else if (amaDetailMatcher.find()){
                // TODO: 2019/3/21 暂时无法跳转 详情页需要时间参数 具体可见 BBSAMAExtendActivity.java
                //问答详情页面
                String tid = amaDetailMatcher.group(1);
                deeplinkScheme = deeplinkScheme + "ama?tid=" + tid ;
            }else if (askMatcher.find()){
                //问答列表页面
                deeplinkScheme = deeplinkScheme + "bbs/forum?fid=42";
            }else if (askDetailMatcher.find()){
                //问答详情页面
                String tid = askDetailMatcher.group(1);
                deeplinkScheme = deeplinkScheme + "bbs/detail?tid=" + tid ;
            }else if (postMatcher.find()){
                //论坛帖子详情页面
                String tid = postMatcher.group(1);
                deeplinkScheme = deeplinkScheme + "bbs/detail?tid=" + tid ;
            }else if (activitiesMatcher.find()){
                //所有活动列表页面
                deeplinkScheme = deeplinkScheme + "bbs/forum?fid=118";
            }else if (activityMatcher.find()){
                //活动详情页面
                deeplinkScheme = deeplinkScheme+"activity?tid="+activityMatcher.group(1);
            }else if (forumMatcher.find()){
                //各个板块
                String fid = forumMatcher.group(1);
                deeplinkScheme = deeplinkScheme + "bbs/forum?fid=" + fid ;
            }else if (docMatcher.find()){
                //文库
                String id = docMatcher.group(1);
                deeplinkScheme = deeplinkScheme + "bbs/doc?tid=" + id;
            }else if (tutorialMatcher.find()) {
                //教程详情
                String id = tutorialMatcher.group(1);
                deeplinkScheme = deeplinkScheme + "bbs/tutorial?tid=" + id;
            }else if(chainthingMatcher.find()){
                String id = chainthingMatcher.group(1);
                deeplinkScheme = deeplinkScheme + "mall/item?id=" + id;
            }else {
                deeplinkScheme = deeplinkScheme + "unknow?source="+url;
            }
        }else if ("www.8btc.com".equals(uri.getHost())) {
            //新版资讯帖子详情
            String articleReg = "/article/([0-9]+)|/media/([0-9]+)|/business/([0-9]+)";
            Matcher articleMatcher = Pattern.compile(articleReg).matcher(uri.getPath());

            //资讯视频
            String videoReg = "/video/([0-9]+)";
            Matcher videoMatcher = Pattern.compile(videoReg).matcher(uri.getPath());
            //资讯专题
            String specialReg = "/special/([0-9]+)";
            Matcher specialMatcher = Pattern.compile(specialReg).matcher(uri.getPath());
            //资讯周刊
            String weeklyReg = "/weekly/([0-9]+)";
            Matcher weeklyMatcher = Pattern.compile(weeklyReg).matcher(uri.getPath());

            //作者详情页 TODO 为定义！
            String authorReg = "/author/([0-9]+)/";
            Matcher authorMather = Pattern.compile(authorReg).matcher(uri.getPath());

            if (articleMatcher.find()) {
                String tid = articleMatcher.group(1);
                deeplinkScheme = deeplinkScheme + "news/detail?tid=" + tid + "&source=" + Uri.encode(url);
            } else if (videoMatcher.find()) {
                String tid = videoMatcher.group(1);
                deeplinkScheme = deeplinkScheme + "news/detail?tid=" + tid + "&source=" + Uri.encode(url);
            } else if (specialMatcher.find()) {
                String tid = specialMatcher.group(1);
                deeplinkScheme = deeplinkScheme + "news/topic?tid=" + tid + "&source=" + Uri.encode(url);
            } else if (weeklyMatcher.find()) {
                String tid = weeklyMatcher.group(1);
                deeplinkScheme = deeplinkScheme + "news/weekly?tid=" + tid + "&source=" + Uri.encode(url);
            } else {
                deeplinkScheme = deeplinkScheme+"unknow?source="+url;
            }
        }else if ("m.8btc.com".equals(uri.getHost())){
            //新版资讯帖子详情
            String articleReg = "/article/([0-9]+)|/media/([0-9]+)|/business/([0-9]+)";
            Matcher articleMatcher = Pattern.compile(articleReg).matcher(uri.getPath());

            //资讯视频
            String videoReg = "/video/([0-9]+)";
            Matcher videoMatcher = Pattern.compile(videoReg).matcher(uri.getPath());
            //资讯专题
            String specialReg = "/special/([0-9]+)";
            Matcher specialMatcher = Pattern.compile(specialReg).matcher(uri.getPath());
            //资讯周刊
            String weeklyReg = "/weekly/([0-9]+)";
            Matcher weeklyMatcher = Pattern.compile(weeklyReg).matcher(uri.getPath());

            //作者详情页 TODO 为定义！
            String authorReg = "/author/([0-9]+)/";
            Matcher authorMather = Pattern.compile(authorReg).matcher(uri.getPath());

            //论坛帖子详情
            String postReg = "/thread-([0-9]+)-([0-9]+)-([0-9]+)\\.html";
            //学院
            String articleOldReg = "/article-([0-9]+)-([0-9]+)\\.html";
            //论坛各板块分类
            String forumReg = "/forum-(\\w+)-([0-9]+)\\.html";
            //文库 研报中心
            String docReg = "/doc-view-([0-9]+).html";
            //学院专题
            String topicReg = "/topic-(.+)\\.html";
            //圈子群主页
            String circleGroupReg = "/im/qr-group";
            //个人圈子主页
            String personalHomeReg = "/im/qr-friend";

            String path = uri.getPath();
            Matcher postMatcher = Pattern.compile(postReg).matcher(path);
            Matcher articleOldMatcher = Pattern.compile(articleReg).matcher(path);
            Matcher forumMatcher = Pattern.compile(forumReg).matcher(path);
            Matcher docMatcher = Pattern.compile(docReg).matcher(path);
            Matcher topicMatcher = Pattern.compile(topicReg).matcher(path);
            Matcher groupDetail = Pattern.compile(circleGroupReg).matcher(path);
            Matcher personHome = Pattern.compile(personalHomeReg).matcher(path);


            if (articleMatcher.find()) {
                String tid = articleMatcher.group(1);
                deeplinkScheme = deeplinkScheme + "news/detail?tid=" + tid + "&source=" + Uri.encode(url);
            } else if (videoMatcher.find()) {
                String tid = videoMatcher.group(1);
                deeplinkScheme = deeplinkScheme + "news/detail?tid=" + tid + "&source=" + Uri.encode(url);
            } else if (specialMatcher.find()) {
                String tid = specialMatcher.group(1);
                deeplinkScheme = deeplinkScheme + "news/topic?tid=" + tid + "&source=" + Uri.encode(url);
            } else if (weeklyMatcher.find()) {
                String tid = weeklyMatcher.group(1);
                deeplinkScheme = deeplinkScheme + "news/weekly?tid=" + tid + "&source=" + Uri.encode(url);
            }else if (postMatcher.find()) {
                String tid = postMatcher.group(1);
                String page = postMatcher.group(2);

                deeplinkScheme = deeplinkScheme + "bbs/detail?tid=" + tid + "&page=" + page;
            } else if (articleOldMatcher.find()) {
                String aid = articleOldMatcher.group(1);
                String page = articleOldMatcher.group(2);

                deeplinkScheme = deeplinkScheme + "bbs/article?aid=" + aid + "&page=" + page;
            } else if (forumMatcher.find()) {
                String fid = forumMatcher.group(1);
                String page = forumMatcher.group(2);

                deeplinkScheme = deeplinkScheme + "bbs/forum?fid=" + fid + "&page=" + page;
            } else if (docMatcher.find()) {
                String id = docMatcher.group(1);
                deeplinkScheme = deeplinkScheme + "bbs/doc?tid=" + id;
            } else if (topicMatcher.find()) {
                String topic = topicMatcher.group(1);

                deeplinkScheme = deeplinkScheme + "bbs/topic?topic=" + topic;
            } else if (groupDetail.find()){
                String id = uri.getQueryParameter("id");
                deeplinkScheme = deeplinkScheme+"im/chatgroup_detail?id="+id;
            }else if (personHome.find()){
                String id = uri.getQueryParameter("id");
                deeplinkScheme = deeplinkScheme+"im/user?id="+id;
            }else {
                deeplinkScheme = deeplinkScheme+"unknow?source="+url;
            }
        }else {
            deeplinkScheme = deeplinkScheme+"unknow?source="+url;
        }

        return deeplinkScheme;
    }

    private static String getNewsDeepLink(String url, Uri uri, String deeplinkScheme) {
        //论坛帖子详情
        String postReg = "/thread-([0-9]+)-([0-9]+)-([0-9]+)\\.html";
        //学院
        String articleReg = "/article-([0-9]+)-([0-9]+)\\.html";
        //论坛各板块分类
        String forumReg = "/forum-(\\w+)-([0-9]+)\\.html";
        //文库 研报中心
        String docReg = "/doc-view-([0-9]+).html";
        //学院专题
        String topicReg = "/topic-(.+)\\.html";
        String normalOtherReg = "/forum.php";
        //个人中心板块

        String path = uri.getPath();
        Matcher postMatcher = Pattern.compile(postReg).matcher(path);
        Matcher articleMatcher = Pattern.compile(articleReg).matcher(path);
        Matcher forumMatcher = Pattern.compile(forumReg).matcher(path);
        Matcher docMatcher = Pattern.compile(docReg).matcher(path);
        Matcher topicMatcher = Pattern.compile(topicReg).matcher(path);
        Matcher normalMatcher = Pattern.compile(normalOtherReg).matcher(path);
        if (postMatcher.find()) {
            String tid = postMatcher.group(1);
            String page = postMatcher.group(2);

            deeplinkScheme = deeplinkScheme + "bbs/detail?tid=" + tid + "&page=" + page;
        } else if (articleMatcher.find()) {
            String aid = articleMatcher.group(1);
            String page = articleMatcher.group(2);

            deeplinkScheme = deeplinkScheme + "bbs/article?aid=" + aid + "&page=" + page;
        } else if (forumMatcher.find()) {
            String fid = forumMatcher.group(1);
            String page = forumMatcher.group(2);

            deeplinkScheme = deeplinkScheme + "bbs/forum?fid=" + fid + "&page=" + page;
        } else if (docMatcher.find()) {
            String id = docMatcher.group(1);
            deeplinkScheme = deeplinkScheme + "bbs/doc?tid=" + id;
        } else if (topicMatcher.find()) {
            String topic = topicMatcher.group(1);

            deeplinkScheme = deeplinkScheme + "bbs/topic?topic=" + topic;
        } else if (normalMatcher.matches()) {
            boolean forceUseHost = false;
            String paramMod = uri.getQueryParameter("mod");
            if (TextUtils.isEmpty(paramMod)) {
                forceUseHost = true;
            } else {
                if ("viewthread".equals(paramMod)) {
                    String tid = uri.getQueryParameter("tid");
                    if (TextUtils.isEmpty(tid)) {
                        forceUseHost = true;
                    } else {
                        deeplinkScheme = deeplinkScheme + "bbs/detail?tid=" + tid;
                    }
                } else if ("forumdisplay".equals(paramMod)) {
                    String fid = uri.getQueryParameter("fid");
                    if (TextUtils.isEmpty(fid)) {
                        forceUseHost = true;
                    } else {
                        deeplinkScheme = deeplinkScheme + "bbs/forum?fid=" + fid;
                    }
                } else if ("view".equals(paramMod)) {
                    String aid = uri.getQueryParameter("aid");
                    if (TextUtils.isEmpty(aid)) {
                        forceUseHost = true;
                    } else {
                        deeplinkScheme = deeplinkScheme + "bbs/article?aid=" + aid;
                    }
                } else if ("topic".equals(paramMod)) {
                    String topic = uri.getQueryParameter("topic");
                    if (TextUtils.isEmpty(topic)) {
                        forceUseHost = true;
                    } else {
                        deeplinkScheme = deeplinkScheme + "bbs/topic?topic=" + topic;
                    }
                }
            }
            if (forceUseHost) {
                deeplinkScheme = deeplinkScheme + "bbs?source=" + Uri.encode(url);
            } else {
                String page = uri.getQueryParameter("page");
                if (!TextUtils.isEmpty(page)) {
                    deeplinkScheme = deeplinkScheme + "&page=" + page;
                }
            }
        } else {
            deeplinkScheme = deeplinkScheme + "bbs?source=" + Uri.encode(url);
        }
        return deeplinkScheme;
    }
}
